package pattern;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * Created with IntelliJ IDEA.
 * Description:线程池的实现
 * User: 东莞呵呵
 * Date:2022-09-22
 * Time:11:09
 */
class MyThreadPool{
    private BlockingQueue<Runnable> blockingQueue=new LinkedBlockingDeque<>();

    public void submit(Runnable runnable) throws InterruptedException {
        this.blockingQueue.put(runnable);
    }

    //初始化的线程池数目
//    public MyThreadPool(int m) throws InterruptedException {
//        for (int i = 0; i < m; i++) {
//            Thread t=new Thread(blockingQueue.take());
//            t.start();
//        }
//    }

//    public MyThreadPool(int m) {
//        // 在构造方法中, 创建出 M 个线程. 负责完成工作.
//        for (int i = 0; i < m; i++) {
//            Thread t = new Thread(() -> {
//                while (true) {
//                    try {
//                        Runnable runnable = blockingQueue.take();
//                        runnable.run();
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
//                }
//            });
//            t.start();
//        }
//    }

    public MyThreadPool(int m) throws InterruptedException {
        for (int i = 0; i < m; i++) {
            Thread t=new Thread(){
                @Override
                public void run() {
                    while(true){
                        try {
                            Runnable runnable=blockingQueue.take();
                            runnable.run();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            };
            t.start();
        }
    }
}


public class Demo6 {
    public static void main(String[] args) throws InterruptedException {
        MyThreadPool pool = new MyThreadPool(10);
        for (int i = 0; i < 1000; i++) {
            int taskId = i;
            pool.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println("执行当前任务: " + taskId + " 当前线程: " + Thread.currentThread().getName());
                }
            });
        }
    }
}
